package com.itheima.reggie.controller;

import com.itheima.reggie.commons.R;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.pojo.Page;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.service.LoginService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Api(tags ="员工类")
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController extends BaseController{
    @Autowired
    private LoginService loginService;
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee) {
        //1.调用业务层实现登录
        R<Employee> result = loginService.login(employee);
        //2.如果返回1则登录成功
        if (result.getCode() == 1) {
            //3.将员工信息的id放在会话域中
            session.setAttribute("LOGIN_ID", result.getData().getId());
        }
        //3.返回登录结果
        return result;
    }
    @PostMapping("/logout")
    public R<String> logout(){
        session.invalidate();
        return R.success("退出成功");
    }
    @GetMapping("page")
    public R<Page<Employee>> page(@RequestParam("page") Integer pageNum, Integer pageSize, String name) {
        Page<Employee> page = employeeService.findByPage(pageNum, pageSize, name);
        return R.success(page);
    }
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //1. 从会话域中获取登陆者
        Long id = getLoginIdFromSession();
        //2. 设置创建和更新的用户ID
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        //3. 调用业务层保存员工
        employeeService.save(employee);
        return R.success("添加员工成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        if (employee.getId()==1&&employee.getStatus()==0){
            throw new CustomException("不能修改管理员");
        }
        //3. 把信息交给service进行更新操作
        employeeService.update(employee);
        //4. 返回修改成功
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.findById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

}
